<?php
/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: CategoryController.php 3075 2010-05-26 15:41:59Z quanvo $
 */

class Shop_CategoryController extends Zend_Controller_Action
{
    /* ========== Backend actions =========================================== */

    /**
    * Add new category
    *
    * @return void
    */
    public function addAction()
    {
        $this->view->addHelperPath(TOMATO_APP_DIR . DS . 'modules' . DS . 'upload' . DS . 'views' . DS . 'helpers', 'Upload_View_Helper_');

        //get database connection
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        //show selectbox
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        //get language
        /*$lanuguages = $categoryDao->getLanguage();
        $this->view->assign('languages', $lanuguages);*/

        //get defautl language
        $config = Tomato_Config::getConfig();
        $lang = $config->web->lang;
        $this->view->assign('lang', $lang);
        //get current datetime
        $date = date('d/m/Y');
        $this->view->assign('date', $date);

        $request = $this->getRequest();
        if ($request->isPost()) {

            $category_admin_name           = $request->getPost('category_admin_name');
            $category_status               = $request->getPost('category_status');
            $category_image             = $request->getPost('category_image');
            $category_enable_product    = $request->getPost('category_enable_product');
            $parentId                     = $request->getPost('parentId');

            $purifier = new HTMLPurifier();

            $category = new Shop_Models_Category(array(
                'category_parent_id'    => $parentId,
                'category_admin_name'    => $purifier->purify($category_admin_name),
                'category_status'           => $category_status,
                'category_image'           => $category_image,
                'category_enable_product' => $category_enable_product,
                'category_created_date' => date('Y-m-d H:i:s'),
                'category_modified_date' => date('Y-m-d H:i:s')
            ));
            $id = $categoryDao->add($category, $parentId);
            if ($id > 0) {
                $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('category_add_success')
                );
                //$this->_redirect($this->view->serverUrl().$this->view->url(array(), 'shop_category_add'));
                $this->_redirect($this->view->serverUrl().$this->view->url(array('category_id' => $id), 'shop_category_edit'));
            }
        }
    }

    /**
    * List categories
    *
    * @return void
    */
    public function listAction()
    {
        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category models access to data
        **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Category content model access to data
         **/
        $categoryContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryContentDao();
        $categoryContentDao->setDbConnection($conn);

        /**
        * Get category tree follow level
        **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        /**
         * Get category content
         * $arrCategoryContentName Store category name each language
         **/
        $arrCategoryContentName = array();
        foreach ($categories as $row){
            $category_content = $categoryContentDao->getCategoryContentByCategoryId($row->category_id, "cc.language_code DESC");
            $strCategoryContentName = '';
            $i = 0;
            foreach ($category_content as $row1){
                $i++;
                if(count($category_content) == $i){
                    $strCategoryContentName .= $row1->category_content_name." ({$row1->language_name})";
                }
                else{
                    $strCategoryContentName .= $row1->category_content_name." ({$row1->language_name})<br>";
                }
            }
            $arrCategoryContentName[$row->category_id] = $strCategoryContentName;
        }
        $this->view->assign('arrCategoryContentName', $arrCategoryContentName);
    }

    /**
    * Update categories
    *
    * @return void
    */
    public function editAction()
    {
        $request = $this->getRequest();
        $id      = $request->getParam('category_id');
        $this->view->assign('id', $id);

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category models access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Category content models access to data
         **/
        $categoryContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryContentDao();
        $categoryContentDao->setDbConnection($conn);

        /**
         * Get language list of system
         **/
        $lanuguages = $categoryDao->getLanguage();
        $this->view->assign('languages', $lanuguages);

        /**
         * Get category each level to selectbox view
         **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        /**
         * Get current date
         **/
        $date = date('d/m/Y');
        $this->view->assign('date', $date);

        /**
         * Get category info for edit
         **/
        $category = $categoryDao->getCategoryById($id);
        $this->view->assign('category', $category);

        /**
         * Get category conten to view for edit
         * $arrCategoryByLanguage : Store category info follow language
         **/
        $category_content = $categoryContentDao->getCategoryContentByCategoryId($id);
        $arrCategoryByLanguage = array();
        foreach ($category_content as $row){
            $arrCategoryByLanguage[$row->language_code] = $row;
        }
        $this->view->assign('arrCategoryByLanguage', $arrCategoryByLanguage);

        if ($request->isPost()) {
            $deleteCategory       = true;

            $category_admin_name           = $request->getPost('category_admin_name');
            $category_status               = $request->getPost('category_status');
            $category_image             = $request->getPost('category_image');
            $category_enable_product    = $request->getPost('category_enable_product');
            $parentId                     = $request->getPost('parentId');
            $includeChildCategory = false;

            $purifier = new HTMLPurifier();

            $category->category_parent_id      = $parentId;
            $category->category_admin_name     = $purifier->purify($category_admin_name);
            $category->category_status         = $category_status;
            $category->category_enable_product = $category_enable_product;
            $category->category_modified_date  = date('Y-m-d H:i:s');

            $parent = $categoryDao->getParentCategory($category);
            if ((null == $parent && $parentId == 0) || ($parent != null && $parent->category_id == $parentId)) {
                $deleteCategory = false;
            }
            $categoryDao->update($category, $parentId, $deleteCategory, $includeChildCategory);
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                $this->view->translator('category_edit_success')
            );
            $this->_redirect($this->view->serverUrl().$this->view->url(array('category_id' => $id), 'shop_category_edit'));
        }
    }
    public function saveContentAction(){

        $request = $this->getRequest();
        //get connection
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $categoryContentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryContentDao();
        $categoryContentDao->setDbConnection($conn);

        if ($request->isPost()) {

            $category_content_id             = $request->getPost('category_content_id');
            $category_id                     = $request->getParam('category_id');
            $language_code                     = $request->getPost('language_code');
            $category_content_name             = $request->getPost('category_content_name');
            $category_content_friendly_url    = $request->getPost('category_content_friendly_url');
            $category_content_description     = $request->getPost('category_content_description');

            $purifier = new HTMLPurifier();
            $category_content = new Shop_Models_CategoryContent(array(
                'category_id'                    => $category_id,
                'language_code'                       => $language_code,
                'category_content_name'               => $purifier->purify($category_content_name),
                'category_content_friendly_url'    => $purifier->purify($category_content_friendly_url),
                'category_content_description'    => $category_content_description
            ));

            if(!$category_content_id){
                $id = $categoryContentDao->addContent($category_content);
                if ($id > 0) {
                    $this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('category_add_success')
                    );
                    $this->_redirect($this->view->serverUrl().$this->view->url(array('category_id' => $category_id), 'shop_category_edit'));
                }
            }else{
                $categoryContentDao->editContent($category_content,$category_content_id);
                $this->_helper->getHelper('FlashMessenger')->addMessage($this->view->translator('category_add_success'));
                $this->_redirect($this->view->serverUrl().$this->view->url(array('category_id' => $category_id), 'shop_category_edit'));
            }
        }

    }
    public function deleteAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request  = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getPost('id');
            /**
             * Get connection to database
             **/
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();

            /**
             * Category models access to data
             **/
            $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
            $categoryDao->setDbConnection($conn);

            /**
             * Get category info for delete
             **/
            $category = $categoryDao->getCategoryById($id);

            if ($category != null) {

                /**
                 * get all attributes to check category is used
                 **/
                $attributes = $categoryDao->getAllAttributes();
                $att_used = false;
                foreach($attributes as $row){
                    if(strstr($row->category_id, ",{$id},")){
                        $att_used = true;
                        break;
                    }
                }

                /**
                 * get all products to check category is used
                 **/
                $products = $categoryDao->getAllProducts();
                $pd_used = false;
                foreach($products as $row){
                    if(strstr($row->category_id, ",{$id},")){
                        $pd_used = true;
                        break;
                    }
                }

                /**
                 * delete category
                 **/
                if(!$att_used && !$pd_used){
                    $categoryDao->delete($category);
                    $response = 'RESULT_OK';
                }else{
                    $response = 'RESULT_IS_USED';
                }
            }
        }
        $this->getResponse()->setBody($response);
    }

    /**
    * Update categories' order
    *
    * @since 2.0.7
    * @return void
    */
    public function orderAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request  = $this->getRequest();
        if ($request->isPost()) {
            $data = $request->getPost('data');
            $data = Zend_Json::decode($data);

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
            $categoryDao->setDbConnection($conn);

            foreach ($data as $category) {
                $categoryDao->updateOrder(new Shop_Models_Category(array(
                    'category_id' => $category['id'],
                    'category_parent_id'   => $category['parent_id'],
                    'category_left'     => $category['left_id'],
                    'category_right'    => $category['right_id'],
                )));
            }

            $response = 'RESULT_OK';
        }
        $this->getResponse()->setBody($response);
    }
}
